package com.salim.leetcode.$24;

public class SwapNodesinPairs {
    public ListNode swapPairs(ListNode head) {
        if(head==null){
            return null;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        swap(dummy,dummy.next,dummy.next.next);
        return dummy.next;
    }

    public void swap(ListNode left,ListNode middle,ListNode right){
        if(right!=null){
            ListNode nextMiddle = right.next;
            left.next = right;
            right.next = middle;
            middle.next = nextMiddle;
            if(nextMiddle!=null){
                ListNode nextRight = nextMiddle.next;
                swap(middle,nextMiddle,nextRight);
            }
        }else{
            left.next = middle;
        }
    }

    public static void main(String[] args) {
        SwapNodesinPairs swapNodesinPairs = new SwapNodesinPairs();
        ListNode line1 = new ListNode(1);
//        ListNode line2 = new ListNode(2);
//        ListNode line3 = new ListNode(3);
//        ListNode line4 = new ListNode(4);
//        ListNode line5 = new ListNode(5);
//        line1.next = line2;
//        line2.next = line3;
//        line3.next = line4;
//        line4.next = line5;
        ListNode head = swapNodesinPairs.swapPairs(null);
        System.out.println(head.toString());
    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    @Override
    public String toString() {
        String str =  " ["+this.val+"]";
        if(this.next!=null){
            str += this.next.toString();
        }
        return str;
    }
}
